<template>
  <div class="order-detail-page">
    <HeaderNav />
    
    <div class="container" v-loading="loading">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/order/list' }">我的订单</el-breadcrumb-item>
        <el-breadcrumb-item>订单详情</el-breadcrumb-item>
      </el-breadcrumb>

      <div v-if="orderDetail.id" class="order-detail-content">
        <!-- 订单状态 -->
        <div class="order-status-card">
          <div class="status-info">
            <h2>{{ getStatusText(orderDetail.orderStatus) }}</h2>
            <p v-if="orderDetail.orderNo">订单号：{{ orderDetail.orderNo }}</p>
          </div>
          <div class="status-actions" v-if="orderDetail.paymentStatus === 0 && orderDetail.orderStatus !== 4 && orderDetail.orderStatus !== 5">
            <el-button type="primary" @click="handlePay">立即支付</el-button>
            <el-button type="danger" plain @click="handleCancel">取消订单</el-button>
          </div>
        </div>

        <!-- 物流信息 -->
        <div v-if="orderDetail.logistics && orderDetail.orderStatus !== 5" class="logistics-card">
          <h3 class="card-title">物流信息</h3>
          
          <!-- 4节点物流进度条 -->
          <div class="logistics-timeline">
            <div 
              v-for="(step, index) in orderDetail.logistics.steps" 
              :key="index"
              class="timeline-node"
              :class="{ active: step.completed, current: isCurrentStep(step, index) }"
            >
              <div class="node-icon">
                <i v-if="step.completed" class="el-icon-check"></i>
                <i v-else-if="isCurrentStep(step, index)" class="el-icon-loading"></i>
                <span v-else>{{ index + 1 }}</span>
              </div>
              <div class="node-content">
                <div class="node-title">{{ step.title }}</div>
                <div class="node-time" v-if="step.time">{{ formatTime(step.time) }}</div>
              </div>
              <div v-if="index < orderDetail.logistics.steps.length - 1" class="node-line"></div>
            </div>
          </div>

          <!-- 取件码（仅待取件状态显示） -->
          <div v-if="orderDetail.logistics.pickupCode" class="pickup-code-section">
            <div class="pickup-code-card">
              <div class="pickup-code-label">取件码</div>
              <div class="pickup-code-value">{{ orderDetail.logistics.pickupCode }}</div>
              <div class="pickup-code-tip">请凭此取件码到指定地点取件</div>
            </div>
          </div>

          <!-- 物流详细信息 -->
          <div class="logistics-details">
            <div class="detail-item" v-if="orderDetail.trackingNumber">
              <span class="detail-label">物流单号：</span>
              <span class="detail-value">{{ orderDetail.trackingNumber }}</span>
            </div>
            <div class="detail-item" v-if="orderDetail.shippingCompany">
              <span class="detail-label">物流公司：</span>
              <span class="detail-value">{{ orderDetail.shippingCompany }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">当前状态：</span>
              <span class="detail-value status-text">{{ orderDetail.logistics.statusDesc || getLogisticsStatusText(orderDetail.logistics.logisticsStatus) }}</span>
            </div>
          </div>
        </div>

        <!-- 收货信息 -->
        <div class="info-card">
          <h3 class="card-title">收货信息</h3>
          <div class="info-content">
            <p><span class="label">收货人：</span>{{ orderDetail.receiverName }}</p>
            <p><span class="label">联系电话：</span>{{ orderDetail.receiverPhone }}</p>
            <p><span class="label">收货地址：</span>{{ orderDetail.receiverAddress }}</p>
          </div>
        </div>

        <!-- 订单明细 -->
        <div class="info-card">
          <h3 class="card-title">订单明细</h3>
          <div class="order-items">
            <div
              v-for="item in orderDetail.orderItems"
              :key="item.id"
              class="order-item"
            >
              <img
                :src="getImageUrl(item.productImage)"
                :alt="item.productName"
                class="item-image"
                @error="handleImageError"
              />
              <div class="item-info">
                <h4 class="item-name">{{ item.productName }}</h4>
                <div class="item-spec">
                  <span>单价：¥{{ formatPrice(item.unitPrice) }}</span>
                  <span>数量：{{ item.quantity }}</span>
                </div>
              </div>
              <div class="item-total">
                ¥{{ formatPrice(item.totalPrice) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 订单信息 -->
        <div class="info-card">
          <h3 class="card-title">订单信息</h3>
          <div class="info-content">
            <p><span class="label">订单金额：</span>¥{{ formatPrice(orderDetail.totalAmount) }}</p>
            <p v-if="orderDetail.discountAmount > 0">
              <span class="label">优惠金额：</span>¥{{ formatPrice(orderDetail.discountAmount) }}
            </p>
            <p><span class="label">实付金额：</span>¥{{ formatPrice(orderDetail.actualAmount) }}</p>
            <p><span class="label">支付状态：</span>{{ orderDetail.paymentStatus === 1 ? '已支付' : '未支付' }}</p>
            <p><span class="label">支付方式：</span>余额支付</p>
            <p v-if="orderDetail.remark"><span class="label">订单备注：</span>{{ orderDetail.remark }}</p>
            <p><span class="label">下单时间：</span>{{ formatTime(orderDetail.createTime) }}</p>
            <p v-if="orderDetail.shippingTime">
              <span class="label">发货时间：</span>{{ formatTime(orderDetail.shippingTime) }}
            </p>
            <p v-if="orderDetail.completedTime">
              <span class="label">完成时间：</span>{{ formatTime(orderDetail.completedTime) }}
            </p>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-else description="订单不存在" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import HeaderNav from '@/components/HeaderNav.vue'
import { getOrderDetail, payOrder, cancelOrder } from '@/api/order'
import { getImageUrl, handleImageError as handleImgError } from '@/utils/image'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const orderDetail = ref({})

// 加载订单详情
const loadOrderDetail = async () => {
  loading.value = true
  try {
    const orderId = route.params.id
    const res = await getOrderDetail(orderId)
    if (res.code === 200) {
      orderDetail.value = res.data || {}
    } else {
      ElMessage.error(res.message || '订单不存在')
      router.push('/order/list')
    }
  } catch (error) {
    ElMessage.error('加载订单详情失败')
    router.push('/order/list')
  } finally {
    loading.value = false
  }
}

// 处理支付
const handlePay = async () => {
  try {
    // 弹出输入支付密码的对话框
    const result = await ElMessageBox.prompt('请输入支付密码', '确认支付', {
      confirmButtonText: '确认支付',
      cancelButtonText: '取消',
      inputType: 'password',
      inputPlaceholder: '请输入支付密码',
      inputValidator: (value) => {
        if (!value) {
          return '支付密码不能为空'
        }
        if (value.length < 6 || value.length > 20) {
          return '支付密码长度必须在6-20位之间'
        }
        return true
      },
      inputErrorMessage: '请输入正确的支付密码'
    })
    
    const paymentPassword = result.value
    const res = await payOrder(orderDetail.value.id, paymentPassword)
    if (res.code === 200) {
      ElMessage.success('支付成功')
      await loadOrderDetail()
    } else {
      ElMessage.error(res.message || '支付失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('支付失败')
    }
  }
}

// 处理取消订单
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      type: 'warning'
    })
    const res = await cancelOrder(orderDetail.value.id)
    if (res.code === 200) {
      ElMessage.success('取消成功')
      await loadOrderDetail()
    } else {
      ElMessage.error(res.message || '取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '待发货',
    2: '配送中',
    3: '待取件',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取物流状态文本
const getLogisticsStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '待发货',
    2: '配送中',
    3: '待取件',
    4: '已完成'
  }
  return statusMap[status] || '未知'
}

// 判断是否为当前步骤
const isCurrentStep = (step, index) => {
  if (!orderDetail.value.logistics || !orderDetail.value.logistics.steps) {
    return false
  }
  // 当前步骤是第一个未完成的步骤
  const steps = orderDetail.value.logistics.steps
  const currentIndex = steps.findIndex(s => !s.completed)
  return currentIndex === index
}

// 使用统一的图片错误处理
const handleImageError = handleImgError

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return time.replace('T', ' ').substring(0, 19)
}

onMounted(() => {
  loadOrderDetail()
})
</script>

<style scoped lang="scss">
.order-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.order-detail-content {
  .order-status-card {
    background: white;
    border-radius: 8px;
    padding: 30px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .status-info {
      h2 {
        margin: 0 0 10px 0;
        color: #333;
      }
      
      p {
        margin: 0;
        color: #999;
      }
    }
    
    .status-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .logistics-card {
    background: white;
    border-radius: 8px;
    padding: 30px;
    margin-bottom: 20px;
    
    .card-title {
      margin: 0 0 30px 0;
      font-size: 18px;
      color: #333;
    }
    
    .logistics-timeline {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 30px;
      
      .timeline-node {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        
        .node-icon {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background: #e4e7ed;
          color: #909399;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 18px;
          font-weight: bold;
          margin-bottom: 10px;
          z-index: 2;
          transition: all 0.3s;
        }
        
        .node-content {
          text-align: center;
          
          .node-title {
            font-size: 14px;
            color: #606266;
            margin-bottom: 5px;
            font-weight: 500;
          }
          
          .node-time {
            font-size: 12px;
            color: #909399;
          }
        }
        
        .node-line {
          position: absolute;
          top: 20px;
          left: 50%;
          width: 100%;
          height: 2px;
          background: #e4e7ed;
          z-index: 1;
          transition: all 0.3s;
        }
        
        &.active {
          .node-icon {
            background: #67c23a;
            color: white;
          }
          
          .node-content .node-title {
            color: #67c23a;
          }
          
          .node-line {
            background: #67c23a;
          }
        }
        
        &.current {
          .node-icon {
            background: #409eff;
            color: white;
            animation: pulse 1.5s infinite;
          }
          
          .node-content .node-title {
            color: #409eff;
            font-weight: bold;
          }
        }
      }
    }
    
    .pickup-code-section {
      margin: 30px 0;
      display: flex;
      justify-content: center;
      
      .pickup-code-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 12px;
        padding: 30px 50px;
        text-align: center;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        
        .pickup-code-label {
          color: rgba(255, 255, 255, 0.9);
          font-size: 14px;
          margin-bottom: 10px;
          letter-spacing: 1px;
        }
        
        .pickup-code-value {
          color: white;
          font-size: 48px;
          font-weight: bold;
          letter-spacing: 8px;
          margin: 10px 0;
          font-family: 'Courier New', monospace;
        }
        
        .pickup-code-tip {
          color: rgba(255, 255, 255, 0.8);
          font-size: 12px;
          margin-top: 10px;
        }
      }
    }
    
    .logistics-details {
      padding-top: 20px;
      border-top: 1px solid #eee;
      
      .detail-item {
        margin: 12px 0;
        color: #606266;
        
        .detail-label {
          color: #909399;
          margin-right: 10px;
        }
        
        .detail-value {
          color: #303133;
          
          &.status-text {
            font-weight: 500;
            color: #409eff;
          }
        }
      }
    }
  }
  
  @keyframes pulse {
    0%, 100% {
      transform: scale(1);
      box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
    }
    50% {
      transform: scale(1.05);
      box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
    }
  }
  
  .info-card {
    background: white;
    border-radius: 8px;
    padding: 30px;
    margin-bottom: 20px;
    
    .card-title {
      margin: 0 0 20px 0;
      font-size: 18px;
      color: #333;
      border-bottom: 2px solid #f5f5f5;
      padding-bottom: 10px;
    }
    
    .info-content {
      p {
        margin: 15px 0;
        color: #666;
        
        .label {
          color: #999;
          margin-right: 10px;
        }
      }
    }
    
    .order-items {
      .order-item {
        display: flex;
        align-items: center;
        padding: 20px 0;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .item-image {
          width: 100px;
          height: 100px;
          margin-right: 20px;
          border-radius: 4px;
          object-fit: cover;
        }
        
        .item-info {
          flex: 1;
          
          .item-name {
            font-size: 16px;
            margin: 0 0 10px 0;
            color: #333;
          }
          
          .item-spec {
            display: flex;
            gap: 20px;
            color: #999;
          }
        }
        
        .item-total {
          font-size: 18px;
          color: #f56c6c;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
